package com.gmail.dengtao.joe.group.transport.impl.filter;

import com.gmail.dengtao.joe.commons.util.ByteUtils;
import com.gmail.dengtao.joe.group.packet.DefaultPacketImpl;
import com.gmail.dengtao.joe.group.packet.Packet;
import com.gmail.dengtao.joe.transport.filter.FilterAdapter;
import com.gmail.dengtao.joe.transport.filter.FilterEntity;
import com.gmail.dengtao.joe.transport.session.Session;

/**
 * Convert plain bytes to Packet.
 * @author <a href="mailto:joe.dengtao@gmail.com">DengTao</a>
 * @version 1.0
 * @since 1.0
 */
public class PacketFilter extends FilterAdapter {
	
	@Override
	public void dataReceived(FilterEntity nextEntity, Session session,
			Object bts) throws Exception {
		
		byte[] buffer = (byte[]) bts;
		
		//byte START_SYMBOL = ByteUtils.getByte(buffer, 0);
		int pos = 1;	// Skip Start Symbol..
		int len = ByteUtils.getInt(buffer, pos);
		pos += ByteUtils.INTEGER_BYTE_LEN;
		int type = ByteUtils.getInt(buffer, pos);
		pos += ByteUtils.INTEGER_BYTE_LEN;
		int pn = ByteUtils.getInt(buffer, pos);
		pos += ByteUtils.INTEGER_BYTE_LEN;
		int sn = ByteUtils.getInt(buffer, pos);
		pos += ByteUtils.INTEGER_BYTE_LEN;
		byte mf = ByteUtils.getByte(buffer, pos);
		pos += ByteUtils.BYTE_LEN;
		byte[] data = ByteUtils.cut(buffer, pos, len - 1 - pos);
		//byte END_SYMBOL = ByteUtils.getByte(buffer, len - 1);
		
		Packet packet = new DefaultPacketImpl(type, pn, sn, mf, data);
		super.dataReceived(nextEntity, session, packet);
	}

}